package com.sduept.nwld.dataserver.controller.statistics;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.core.dao.SuperDAO;
import com.sduept.nwld.dataserver.manager.statistics.ResponseFeaProtectManager;
import com.sduept.nwld.dataserver.model.countanalyse.ProtectResponseTimeStatistics;

@Named
@ViewScoped
public class ResponseFeaProtectController extends AbstractController {
	
	private static final long serialVersionUID = 8544905069497815139L;
	@Autowired
	private ResponseFeaProtectManager manager;
	@Autowired
	private SuperDAO dao;
	@Autowired
	private CommonDocumentProperties pros;
	private List<String> years = new ArrayList<String>();
	private String year = new String();
	private List<String> areas = new ArrayList<String>();
	private String area = "all";
	private List<ProtectResponseTimeStatistics> protectResponseTimeStatisticsList = new ArrayList<ProtectResponseTimeStatistics>();
	private ProtectResponseTimeStatistics protectResponseTimeStatistics = new ProtectResponseTimeStatistics();
	private ProtectResponseTimeStatistics selected = new ProtectResponseTimeStatistics();
	
	private StreamedContent templateFile;
	
	@PostConstruct
	public void init() {
		initYears();
	}
	
	private void initYears() {
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		
		List<Integer> iyears = (List<Integer>) manager.getRecordsBySql("select DISTINCT year from t_count_protect_response_time_statistics order by year ASC");
		if(!iyears.contains(year)) {
			iyears.add(year);
		}
		int max = iyears.get(iyears.size()-1);
		int min = iyears.get(0);
		years.add(min+"~"+max);
		for (Integer s : iyears) {
			years.add(String.valueOf(s));
		}
	}
	
	public void initProtectResponseTimeStatistics() {
		areas = (List<String>) manager.getRecordsBySql("select DISTINCT area from t_count_protect_response_time_statistics order by area");
		protectResponseTimeStatisticsList = manager.findAll();
	}
	
	public void preCreatProtectResponseTimeStatistics() {
		protectResponseTimeStatistics = new ProtectResponseTimeStatistics();
	}
	
	public void editProtectResponseTimeStatistics() {
		protectResponseTimeStatistics = selected;
	}
	
	public void saveProtectResponseTimeStatistics() {
		if(protectResponseTimeStatistics != null) {
			if(protectResponseTimeStatistics.getId() == null) {//新建
				if(isNotExit(protectResponseTimeStatistics)) {
					ProtectResponseTimeStatistics prts = manager.createOrUpdate(protectResponseTimeStatistics);
					protectResponseTimeStatisticsList.add(prts);
				} else {
					addErrorMessage("记录已存在，添加失败！");
					return;
				}
			} else {//编辑
				protectResponseTimeStatisticsList.set(protectResponseTimeStatisticsList.indexOf(protectResponseTimeStatistics), protectResponseTimeStatistics);
				manager.createOrUpdate(protectResponseTimeStatistics);
				selected = new ProtectResponseTimeStatistics();
			}
			addSuccessMessage("保存成功！");
			years.clear();
			initYears();
			areas.clear();
			initProtectResponseTimeStatistics();
		}
	}
	
	private boolean isNotExit(ProtectResponseTimeStatistics p) {
		boolean flag = false;
		Integer y = p.getYear();
		String area = p.getArea();
		Integer m = p.getMonth();
		List<ProtectResponseTimeStatistics> prts = manager.findByCondition(y, m, area);
		if(prts.size() == 0) {
			//当前记录不存在
			flag = true;
		}
		return flag;
	}
	
	public void deleteProtectResponseTimeStatistics() {
		if(selected != null && !selected.getId().isEmpty()) {
			manager.deleteById(selected.getId());
			protectResponseTimeStatisticsList.remove(selected);
			addSuccessMessage("删除成功！");
			years.clear();
			initYears();
			areas.clear();
			initProtectResponseTimeStatistics();
			selected = new ProtectResponseTimeStatistics();
		} else {
			addErrorMessage("请选择要删除的数据！");
		}
	}
	
	/**
	 * 模板下载
	 */
	public void fileDownloadView() {
		InputStream stream = null;
		try {
			stream = new FileInputStream(new File(pros.getTempletePath()+"countProtectResponseTime.xlsx"));
			templateFile = new DefaultStreamedContent(stream, "xlsx", "countProtectResponseTime.xlsx");
		} catch (FileNotFoundException e) {
			addErrorMessage("下载文件失败，请联系技术人员！");
			e.printStackTrace();
		}
	}

	public void chooseEquipment() {
        Map<String,Object> options = new HashMap<String, Object>();
        options.put("resizable", true);
        options.put("draggable", true);
        options.put("modal", true);
        options.put("width", 600);
        options.put("height", 200);
        
        Map<String,List<String>> params = new HashMap<>();
        List<String> param = new ArrayList<>();
        param.add("1");	//设置去除前几行
        params.put("ingnoreRows", param);
        //openDialog("/ui/common/upload_excel_dialog", params, options);
        openDialog("/ui/common/upload_excel_define", params, options);
    }
	
	public void onSelectorChosen(SelectEvent event) {
		List<List<String>>objs = (List<List<String>>) event.getObject();
		List<ProtectResponseTimeStatistics> temp = new ArrayList<>();
		List<Integer> errorList = new ArrayList<Integer>();
		int i = 0;
		try {
			for (List<String> list : objs) {
				i++;
				//单位	年	月	平均时间	最长动作时间
				ProtectResponseTimeStatistics prts  = new ProtectResponseTimeStatistics();
				int year = NumberFormat.getInstance().parse(list.get(1).toString()).intValue();
				int month = NumberFormat.getInstance().parse(list.get(2).toString()).intValue();
				if(year > 1970 && year < 2200) {
					if(month > 0 && month < 13) {
						prts.setArea(list.get(0));
						prts.setYear(year);
						prts.setMonth(month);
						prts.setAvgActTime(list.get(3));
						prts.setMaxActTime(list.get(4));
						temp.add(prts);
					} else {
						errorList.add(i);
						continue;
					}
				} else {
					errorList.add(i);
					continue;
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
			addErrorMessage("表格数字有误，请仔细核对！");
			return ;
		}
		if(temp.size() !=0) {
			for(ProtectResponseTimeStatistics act:temp) {
				if(isNotExit(act)) {
					manager.createOrUpdate(act);
				}
			}
			years.clear();
			initYears();
			addSuccessMessage("文件上传成功");
		}
		if(errorList.size() != 0) {
			String errorRecord = "";
			for(int j = 0; j<errorList.size(); j++) {
				errorRecord += errorList.get(j) + " ";
			}
			addErrorMessage("文件第"+errorRecord+"行有误，上传失败");
		}
		protectResponseTimeStatisticsList = manager.findAll();
	}
	
	public void search() {
		String sql = "from ProtectResponseTimeStatistics where 1=1 ";
		if(!("all".equals(area))) {
			sql += "and area = '"+area+"' ";
		}
		if("".equals(year)) {
			year = years.get(0);
		}
		if(!(years.get(0).equals(year))) {
			String s = year.substring(0, 4);
			sql += " and year = '"+s+"' ";
		}
		protectResponseTimeStatisticsList = dao.findByComplexCondition(sql, ProtectResponseTimeStatistics.class);
	}
	
	public void reset() {
		area = "all";
		year = years.get(0);
		search();
	}
	
	public void onRowSelect(SelectEvent event) {
		selected = (ProtectResponseTimeStatistics) event.getObject();
	}
	
	public List<String> completeArea(String query) {
		return areas;
	}
	
	public void selectedQueryYear() {
		FacesContext cont = FacesContext.getCurrentInstance();
		Map<String, String> map = cont.getExternalContext().getRequestParameterMap();
		year = map.get("year");
	}
	
	public void changeYear() {
		
	}
	
	public List<ProtectResponseTimeStatistics> getProtectResponseTimeStatisticsList() {
		return protectResponseTimeStatisticsList;
	}

	public void setProtectResponseTimeStatisticsList(
			List<ProtectResponseTimeStatistics> protectResponseTimeStatisticsList) {
		this.protectResponseTimeStatisticsList = protectResponseTimeStatisticsList;
	}

	public ProtectResponseTimeStatistics getProtectResponseTimeStatistics() {
		return protectResponseTimeStatistics;
	}

	public void setProtectResponseTimeStatistics(
			ProtectResponseTimeStatistics protectResponseTimeStatistics) {
		this.protectResponseTimeStatistics = protectResponseTimeStatistics;
	}

	public List<String> getYears() {
		return years;
	}

	public void setYears(List<String> years) {
		this.years = years;
	}

	public StreamedContent getTemplateFile() {
		return templateFile;
	}

	public void setTemplateFile(StreamedContent templateFile) {
		this.templateFile = templateFile;
	}

	public String getArea() {
		return area;
	}

	public void setArea(String area) {
		this.area = area;
	}

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	public List<String> getAreas() {
		return areas;
	}

	public void setAreas(List<String> areas) {
		this.areas = areas;
	}

	public ProtectResponseTimeStatistics getSelected() {
		return selected;
	}

	public void setSelected(ProtectResponseTimeStatistics selected) {
		this.selected = selected;
	}
	
}
